<?php

namespace App\Models\Train\TrainSeat\Repositories;

use App\Models\Train\TrainSeat\TrainSeat;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class TrainSeatRepository extends BaseRepository implements Interfaces\TrainSeatRepositoryInterface
{
    public function __construct(TrainSeat $trainSeat)
    {
        parent::__construct($trainSeat);
    }

    public function addTrainSeat(array $data): TrainSeat
    {
        $train_seat = $this->findByTrainCodeAndSeatName($data['train_code'], $data['from_code'], $data['to_code'], $data['seat_name']);
        if ($train_seat) {
//            if($train_seat->getSeatPrice() < $data['seat_price']){
            $this->updateAndRefreshList($train_seat, $data);
//            }
            return $train_seat;
        }
        $seat = $this->create($data);
        $this->appendCachedSeats($seat);
        return $seat;
    }

    public function findByTrainCodeAndSeatName(string $train_code, string $from_code, string $to_code, string $seat_name): TrainSeat|null
    {
        $cache_key = "Train:Seat:{$train_code}:{$from_code}:{$to_code}:{$seat_name}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }

        $train_seat = $this->findOneBy([
            'train_code' => $train_code,
            'from_code'  => $from_code,
            'to_code'    => $to_code,
            'seat_name'  => $seat_name,
        ]);
        if ($train_seat) {
            Cache::put($cache_key, $train_seat, 5 * config('trip.ttl.day'));
        }
        return $train_seat;
    }

    public function updateAndRefreshList(TrainSeat $train_seat, array $data)
    {
        $this->update($data, $train_seat);
        $this->appendCachedSeats($train_seat);
    }

    private function appendCachedSeats(TrainSeat $seat)
    {
        $seats_cache_key = "Train:Seats:{$seat['train_code']}:{$seat['from_code']}:{$seat['to_code']}";
        if (Cache::has($seats_cache_key)) {
            $seats = Cache::get($seats_cache_key);
            $seats->add($seat);
            Cache::put($seats_cache_key, $seats, 5 * config('trip.ttl.day'));
        }
    }

    public function listByTrainCode(string $train_code, string $from_code, string $to_code): Collection
    {
        $cache_key = "Train:Seats:{$train_code}:{$from_code}:{$to_code}";
        if (Cache::has($cache_key)) {
//            return Cache::get($cache_key);
        }
        $seats = $this->findBy([
            'train_code' => $train_code,
            'from_code'  => $from_code,
            'to_code'    => $to_code,
        ]);

        if (collect($seats)->count() > 0) {
            Cache::put($cache_key, $seats, 5 * config('trip.ttl.day'));
        }
        return $seats;
    }
}